//
//  DepartViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/5/12.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "DepartViewController.h"
#import "TopBackView.h"
#import "RootViewController.h"
#import "DepartCell.h"
#import "Common.h"
#import "AddressVC.h" //常用发车 送达地址
#import "DepartModel.h"
#import "AddressEditVC.h"//编辑 常用地址
#import "WKProgressHUD.h"

@interface DepartViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) UILabel *defaultL;

@property (nonatomic,copy) NSString *addressType;

@property (nonatomic,strong) UIView *nullView;

@property (nonatomic,strong) WKProgressHUD *hud;

@end

@implementation DepartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;


    self.dataArray = [NSMutableArray array];
    
    [self initNullView];
    
    NSString *string;
    if ([self.topTitle isEqualToString:@"0"]) {
        string = @"常用发车地址管理";
    } else {
       string = @"常用送达地址管理";
    }
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:string];
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    topBackView.rightButton.hidden = YES;
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = GrayColor;
    
    [self initTableView];
}

-(void)initNullView
{
    self.nullView = [[UIView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight)];
    self.nullView.backgroundColor = GrayColor;
    
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMidX(self.view.frame) - 23, 95, 46, 52)];
    imageV.image = [UIImage imageNamed:@"no_position"];
    
    [self.nullView addSubview:imageV];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageV.frame) + 14, screenWidth, 20)];
    label.textColor = BtnTitleColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = Font(13);
    label.text = @"暂时没有常用地址";
    
    [self.nullView addSubview:label];
    
    
}



-(void)initTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 66 * 2) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    [self.view addSubview:self.tableView];
    
    NSString *string = @"新增地址";
    if ([self.topTitle isEqualToString:@"0"]) {
        self.addressType = @"0";
    } else {
        self.addressType = @"1";

    }
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(18, screenHeight - 79, screenWidth - 36, Button_Height);
    addButton.backgroundColor = YellowColor;
    addButton.titleLabel.font = Font(17);
    addButton.layer.cornerRadius = 5;
    [addButton setTitle:string forState:UIControlStateNormal];
    [addButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addButton) forControlEvents:UIControlEventTouchUpInside];
    
    if (![self.cancelBtn isEqualToString:@"1"]) {
        [self.view addSubview:addButton];

    }
    
    
    self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
    [self initDataSource];
}

-(void)initDataSource
{
    //订单状态接口
    NSString *urlString = [NSString stringWithFormat:@"%@useraddress/list?addresstype=%@",Main_interface,self.addressType];

    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        
        if ([responseObj[@"success"] boolValue]) {
            
            
            if (self.dataArray.count > 0) {
                
                [self.nullView removeFromSuperview];
                
                [self.dataArray removeAllObjects];
            } else {
                
                [self.tableView addSubview:self.nullView];

            }
            
            for (id object in responseObj[@"data"]) {
                DepartModel *model = [[DepartModel alloc]init];
                [model setValuesForKeysWithDictionary:object];
                
                [self.dataArray addObject:model];
            }
            
            [self.tableView reloadData];
            
        }
        
        [self.hud dismiss:YES];

        
        
    } failed:^(NSString *errorMsg) {
        
        [self.hud dismiss:YES];
    }];
    


}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *string = @"departCell";
    DepartCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[DepartCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:string];
    }
    
    if (self.dataArray.count > 0) {
        
        cell.model = self.dataArray[indexPath.section];
        

        
    }
    
    
    
    [cell.deleteButton addTarget:self action:@selector(deleteButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteButton.tag = indexPath.section + 350;
    
    
    [cell.defaultButton addTarget:self action:@selector(defaluButtonAciton:) forControlEvents:UIControlEventTouchUpInside];
    cell.defaultButton.tag = indexPath.section + 450;
    
    [cell.editButton addTarget:self action:@selector(editButtonAciton:) forControlEvents:UIControlEventTouchUpInside];
    cell.editButton.tag = indexPath.section + 550;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(CGRectGetMinX(cell.defaultButton.frame), CGRectGetMinY(cell.defaultButton.frame), 75, 20);
    [cell.contentView addSubview:button];
    button.tag = indexPath.section + 200;
    [button addTarget:self action:@selector(select:) forControlEvents:UIControlEventTouchUpInside];
    

    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 119 * kHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark cell按钮事件
-(void)deleteButtonAction:(UIButton *)sender
{
    
    DepartModel *model = [[DepartModel alloc]init];
    model = self.dataArray[sender.tag - 350];

    
    NSString *urlString = [NSString stringWithFormat:@"%@useraddress/delete",Main_interface];
    
    NSDictionary *dic = @{@"id":model.ID};
    
    Common *c = [[Common alloc]init];

    [c afPostRequestWithUrlString:urlString parms:dic finishedBlock:^(id responseObj) {
        
        NSDictionary *dicionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dicionary[@"success"] boolValue]) {
            
            // dicionary[@"message"] 提示删除是否成功
            
#warning 可以添加提示框
            [self.dataArray removeObjectAtIndex:sender.tag - 350];
            
            [self.tableView beginUpdates];

            //删除一个section
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sender.tag - 350] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];
            
            [self initDataSource];
        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];


}



-(void)editButtonAciton:(UIButton *)sender
{
    DepartModel *model = [[DepartModel alloc]init];
    model = self.dataArray[sender.tag - 550];
    
    AddressEditVC *editVC = [[AddressEditVC alloc]init];
    
    if ([self.topTitle isEqualToString:@"0"]) {
        
        editVC.addresstype = @"0";
        
        
    } else {
        
        editVC.addresstype = @"1";
        
    }
    
    if ([model.comment isEqual:[NSNull null]]) {
        model.comment = @" ";
    }
    
    editVC.orderId = model.ID;
    editVC.comment = model.comment;
    editVC.isDefault = model.isDefault;
    editVC.contact = model.contact;
    editVC.phone = model.phone;
    editVC.address = model.address;
//    editVC.unitName = model.unitName;
    editVC.provinceName = model.provinceName;
    editVC.provinceCode = model.provinceCode;
    editVC.cityName = model.cityName;
    editVC.cityCode = model.cityCode;
    editVC.countyName = model.countyName;
    editVC.countyCode = model.countyCode;
    
    if ([model.provinceName isEqualToString:model.cityName]) {
        editVC.zoneName = [NSString stringWithFormat:@"%@",model.provinceName];

    } else {
        editVC.zoneName = [NSString stringWithFormat:@"%@-%@",model.provinceName,model.cityName];
 
    }
    

    [self.navigationController pushViewController:editVC animated:YES];

}

-(void)select:(UIButton *)sender
{
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:sender.tag - 200];
    
    DepartCell *cell = (DepartCell *)[self.tableView cellForRowAtIndexPath:index];

    
    cell.defaultButton.tag = index.section + 450;
    [self defaluButtonAciton:cell.defaultButton];
    
}

-(void)defaluButtonAciton:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    DepartModel *model = [[DepartModel alloc]init];
    model = self.dataArray[sender.tag - 450];
    
    NSDictionary *dic = @{@"id":model.ID};
    
    Common *c = [[Common alloc]init];
    
    [c afPostRequestWithUrlString:userAddress_default parms:dic finishedBlock:^(id responseObj) {
        
        NSDictionary *dicionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        
        if ([dicionary[@"success"] boolValue]) {
            
            
#warning 可以添加提示框
            
            [self initDataSource];

        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

    
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
    [self initDataSource];
    
}


-(void)addButton
{
    
    AddressVC *addressVC = [[AddressVC alloc]init];

    if ([self.topTitle isEqualToString:@"0"]) {
       
        addressVC.addresstype = @"0";

    } else {
        
        addressVC.addresstype = @"1";

    }
    addressVC.navtitle = @"2";
    
    addressVC.backString = @"1";
    
    [self.navigationController pushViewController:addressVC animated:YES];
    

}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
